<?php

namespace App\Http\Middleware;

use Closure;
use App\Exceptions\ApiException;
use Illuminate\Support\Facades\Cache;
use App\Models\AdminMenu;

class CheckPermissions
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     * @throws ApiException
     */
    public function handle($request, Closure $next)
    {
        $ticket = $request->input('ticket');
        $user_info = Cache::get($ticket);
        if(empty($user_info)) {
            return  json_error('暂未登录');
        }
        if(empty($user_info['permissions'])) {
            return  json_error('没有权限访问');
        }
        // 拿到菜单ID与角色的权限对比
        if($user_info['permissions'] != '*') {
            $api_name = explode('/', $request->path());
            $has_permissions = AdminMenu::select(['id'])->where(['uri' => $api_name[1]])->get();

            if(!$has_permissions) {
                throw new ApiException('没有权限访问');
            }
            $permissions_list = explode(',', $user_info['permissions']);
            $is_has = false;
            foreach ($has_permissions as $permissions) {
                if(in_array($permissions->id, $permissions_list)) {
                    $is_has = true;
                }
            }
            if(!$is_has) {
                throw new ApiException('没有权限访问');
            }
        }

        return $next($request);
    }
}
